package com.ifar.audiosdk.base

import android.content.Intent
import android.os.Bundle
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.lifecycle.ViewModelProvider
import org.simple.eventbus.EventBus

abstract class IfarBaseFragment<VM : IfarBaseViewModel> : androidx.fragment.app.Fragment() {

    protected lateinit var mViewModel: VM

    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        return inflater.inflate(getLayoutResId(), container, false)
    }

    private var isCreate = false
    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        isCreate = true
        initVM()
        initView()
        initData()
        startObserve()
        super.onViewCreated(view, savedInstanceState)
        EventBus.getDefault().register(this)
    }

    /**
     * viewpager 切换本Fragment时，会调用这个函数，即是否可见，另外需要注意setUserVisibleHint 一开始的状态不准确，
     * 需要配合onViewCreated 来判断何时来刷新数据
     */
    override fun setUserVisibleHint(isVisibleToUser: Boolean) {
        super.setUserVisibleHint(isVisibleToUser)

        if (isVisibleToUser && isCreate) {
            isVisiableToUser(true)
            Log.d("BaseFragment", "fragment 切换")
        }
    }


    /**
     * 正常情况下的切换   add fragment 时有效
     * @author: brian
     * @date:  2019/8/14
     **/
    override fun onHiddenChanged(hidden: Boolean) {
        super.onHiddenChanged(hidden)
        changeToVisiable(!hidden)
    }

    open fun changeToVisiable(isVisibleToUser: Boolean) {}
    open fun isVisiableToUser(isVisibleToUser: Boolean) {}

    open fun startObserve() {}
    abstract fun getLayoutResId(): Int

    abstract fun initView()

    abstract fun initData()
    protected fun startActivity(z: Class<*>) {
        startActivity(Intent(this.context, z))
    }

    private fun initVM() {
        providerVMClass()?.let {
            mViewModel = ViewModelProvider(this).get(it)
            lifecycle.addObserver(mViewModel)
        }
    }

    open fun providerVMClass(): Class<VM>? = null

    override fun onDestroy() {
        lifecycle.removeObserver(mViewModel)
        EventBus.getDefault().unregister(this)
        super.onDestroy()
    }

}